@echo off
echo Starting application packaging...

REM Activate virtual environment
call .venv\Scripts\activate

REM Check if UPX exists, if not download it
if not exist "upx\upx.exe" (
    echo Downloading UPX compression tool...
    if not exist "upx" mkdir upx
    powershell -Command "& {Invoke-WebRequest -Uri 'https://github.com/upx/upx/releases/download/v4.2.2/upx-4.2.2-win64.zip' -OutFile 'upx.zip'}"
    powershell -Command "& {Expand-Archive -Path 'upx.zip' -DestinationPath '.' -Force}"
    move upx-4.2.2-win64\*.* upx\
    rmdir upx-4.2.2-win64
    del upx.zip
    echo UPX downloaded successfully.
)

REM Find akshare installation path
python -c "import akshare; import os; print(os.path.dirname(akshare.__file__))" > akshare_path.txt
set /p AKSHARE_PATH=<akshare_path.txt
del akshare_path.txt

echo Found akshare at: %AKSHARE_PATH%

REM Find pyecharts installation path
python -c "import pyecharts; import os; print(os.path.dirname(pyecharts.__file__))" > pyecharts_path.txt
set /p PYECHARTS_PATH=<pyecharts_path.txt
del pyecharts_path.txt

echo Found pyecharts at: %PYECHARTS_PATH%

REM First try without UPX, add UPX later if needed
REM Optional splash image shown by PyInstaller bootloader if available
set SPLASH_OPT=
if exist assets\splash.png (
    set SPLASH_OPT=--splash=assets\splash.png
) else (
    echo No assets\splash.png found. Generating a default splash...
    if not exist assets mkdir assets
    powershell -NoProfile -ExecutionPolicy Bypass -File scripts\gen_splash.ps1 -OutputPath assets\splash.png
    if exist assets\splash.png (
        set SPLASH_OPT=--splash=assets\splash.png
    )
)

pyinstaller --onefile --windowed ^
    --strip ^
    --optimize=2 ^
    --exclude-module=tkinter ^
    --exclude-module=matplotlib ^
    --exclude-module=PIL.ImageTk ^
    --exclude-module=PIL.ImageWin ^
    --hidden-import=talib.stream ^
    --hidden-import=vnpy_sqlite ^
    --hidden-import=akshare ^
    --hidden-import=pyecharts ^
    --add-data="%AKSHARE_PATH%\file_fold;akshare/file_fold" ^
    --add-data="%PYECHARTS_PATH%\datasets;pyecharts/datasets" ^
    --add-data="%PYECHARTS_PATH%\render\templates;pyecharts/render/templates" ^
    --add-data="ui\components\composite\lightweight-charts.standalone.production.js;ui/components/composite" ^
    %SPLASH_OPT% ^
    --name tgtrader_tools main.py

REM If the above works and you want UPX compression, uncomment the lines below:
REM set UPX_DIR=%CD%\upx
REM if exist "%UPX_DIR%\upx.exe" (
REM     echo Applying UPX compression...
REM     "%UPX_DIR%\upx.exe" --best dist\tgtrader_tools.exe
REM )
    
echo Packaging complete. The executable file is located in the dist directory.
if not defined NO_PAUSE pause
